package com.financing.wap.web.controller.api;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.activities.ActivitiesBusinessObject;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.AuthenticationDTO;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAuthenticationService;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.service.IWechatCoreService;
import com.financing.wap.service.impl.ActivitesServiceImpl;
import com.financing.wap.util.Constants;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.util.WeChatGiftXMLUtil;
import com.financing.wap.util.WeChatMpbackRedirectUtil;
import com.financing.wap.util.WeChatRedirectTemplteUtil;
import com.financing.wap.web.controller.BaseController;

/**
 * 微信API
 * 
 * @author lisu
 *
 */
@Controller("weixinController")
@RequestMapping("/api/wechat")
public class WeixinController extends BaseController {

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IWechatCoreService wechatCoreServiceImpl;

	@Autowired
	public IAuthenticationService authenticationService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IUserWechatService userWechatServiceImpl;
	
	@Autowired
	private ActivitesServiceImpl activitesService;

	/**
	 * 针对一个微信开放平台帐号下的应用，同一用户的unionid是唯一的。
	 */
	public static final String WECHAT_OPENID = "wechatUnionid";
	
	/**
	 * 公众号下的openId
	 */
	public static final String OPENID = "openId";
	
	/**
	 * pc端重定向
	 */
	public static final String PC_SEND_REDIRECT = PropertiesUtils.getValue("open_pc_send_redirecti");
	
	/**
	 * wap端重定向
	 */
	public static final String WAP_SEND_REDIRECT = PropertiesUtils.getValue("open_wap_send_redirecti");
	
	/**
	 * stg 重定向
	 */
	public static final String MSTG_SEND_REDIRECT = PropertiesUtils.getValue("mstg_send_redirecti");
	/**
	 * wap端重定向(不前往注册页面，直接前往活动页面)
	 */
	public static final String WAP_SEND_ACTIVITES_REDIRECT = PropertiesUtils.getValue("open_wap_send_fczs_redirecti");
	
	@Autowired
	public IShopperUserInfoService shopperUserInfoService;

	/**

	/**
	 * 开放-扫描二维码回调方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@RequestMapping(value = "/openback")
	public void callback(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		logger.info("In apiweixin opencallback begin!");
		try {
			ResultMap map = wechatCoreServiceImpl
					.openCallback(request);
			StringBuffer userinfo = new StringBuffer();
			
			//输出状态码
			logger.info("In apiweixin opencallback ResultMap getStatusCode!"+map.getStatusCode());
			// 已经关联
			if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_SUCCESS.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");

				UserDTO user = userService.queryUserById(bean.getUserId());

				if (user != null) {
					// 用户状态验证
					if (Constants.FA_STATUS_DISABLE.equals(user.getFaStatus())) {
						logger.info("In apiweixin relationlogin checkUser Status 02");
						// 已经被禁用
						map.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_DISABLE);
						response.sendRedirect(PC_SEND_REDIRECT+map.getStatusCode());
						return ;

					}
					// 已经被拉黑 判断
					if (Constants.FA_STATUS_BLACK.equals(user.getFaStatus())) {
						logger.info("In apiweixin relationlogin checkUser Status 02");
						// 已经被拉黑
						map.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_BLACK);
						response.sendRedirect(PC_SEND_REDIRECT+map.getStatusCode());
						return ;
					}
				}
				logger.info("In apiweixin opencallback set seesion login!");
				Session session = SessionUtil.getSession(true);
				session.setLogin(true);
				session.setUser(user);
				SessionUtil.setSession(session);
				AuthenticationDTO auth = authenticationService
						.queryAuthInfo(user.getId());

				String returnUrl = (String) session.getAttribute("returnUrl");
				Map<String, Object> parameterMap = (Map<String, Object>) session
						.getAttribute("returnParameterMap");
				String returnMethod = (String) session
						.getAttribute("returnMethod");
				userinfo.append("&returnUrl=");
				userinfo.append(StringUtils.isBlank(returnUrl)?returnUrl:URLEncoder.encode(returnUrl));
				userinfo.append("&params=");
				userinfo.append(parameterMap);
				userinfo.append("&method=");
				userinfo.append(StringUtils.isBlank(returnMethod)?returnMethod:URLEncoder.encode(returnMethod));
				userinfo.append("&userType=");
				userinfo.append(user.getUType());
				userinfo.append("&uRole=");
				userinfo.append(user.getRole());
				userinfo.append("&reviewStatus=");
				userinfo.append("0");
				if (auth != null) {
					userinfo.append("&reviewStatus=");
					userinfo.append(StringUtils.isBlank(auth.getReviewStatus())?auth.getReviewStatus():URLEncoder.encode(auth.getReviewStatus()));
				}
				if (StringUtils.isBlank(user.getUserName())) {
					userinfo.append("&uName=");
					userinfo.append("");
				} else {
					userinfo.append("&uName=");
					userinfo.append(StringUtils.isBlank(user.getUserName())?user.getUserName():URLEncoder.encode(user.getUserName()));
				}

				FaUserDTO userTmp = new FaUserDTO();
				userTmp.setId(user.getId());
				userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
				userTmp.setLastLoginTime(new Date());
				userTmp.setLoginNum(user.getLoginNum()+1);
				userService.updateFaUserInfo(userTmp);
				userinfo.append("&id=");
				userinfo.append(user.getId());
				userinfo.append("&lastLoginIP=");
				userinfo.append(user.getLastLoginIP());
				userinfo.append("&lastLoginTime=");
				userinfo.append(user.getLastLoginTime());
				userinfo.append("&uImage=");
				userinfo.append(user.getuImage());
				userinfo.append("&loginName=");
				userinfo.append(user.getLoginName());
				userinfo.append("&nickname=");
				userinfo.append(StringUtils.isBlank(bean.getNickname())?bean.getNickname():URLEncoder.encode(bean.getNickname()));
				userinfo.append("&headimgurl=");
				userinfo.append(bean.getHeadimgurl());
				
				//未关联-提示用户关联  将openid 设置到session
			} else if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_WECHAT_ASSOCIATED_USER_ERROR.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");
				userinfo.append("&nickname=");
				userinfo.append(StringUtils.isBlank(bean.getNickname())?bean.getNickname():URLEncoder.encode(bean.getNickname()));
				userinfo.append("&headimgurl=");
				userinfo.append(bean.getHeadimgurl());
				

				//进行下一步关联用户操作.将openid设置到session
				super.getSession(true).setAttribute(WECHAT_OPENID,bean.getUnionid());
			}

			logger.info("In apiweixin opencallback sendRedirect:"+PC_SEND_REDIRECT+map.getStatusCode()+userinfo.toString());
			response.sendRedirect(PC_SEND_REDIRECT+map.getStatusCode()+userinfo.toString());

		} catch (Exception e) {

			logger.error("In apiweixin opencallback error!", e);
		}
		logger.info("In apiweixin opencallback end!");

	}
	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@RequestMapping(value = "/mpback")
	public void mpback(HttpServletRequest request,
			HttpServletResponse response) {

		logger.info("In apiweixin mpback begin!");
		try {
			//判断域名来源
			ResultMap checkMap = checkStg(request,response);
			if (STATUS.FAILE.equals(checkMap.getStatus())){
				return ;
			}
			
			ResultMap map = wechatCoreServiceImpl
					.mpCallback(request);
			StringBuffer userinfo = new StringBuffer();

			//输出状态码
			logger.info("In apiweixin mpback ResultMap getStatusCode!"+map.getStatusCode());
			// 已经关联
			if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_SUCCESS.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");

				UserDTO user = userService.queryUserById(bean.getUserId());

				if (user != null) {
					// 用户状态验证
					if (Constants.FA_STATUS_DISABLE.equals(user.getFaStatus())) {
						logger.info("In apiweixin mpback checkUser Status 02");
						// 已经被禁用
						map.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_DISABLE);
						response.sendRedirect(WAP_SEND_REDIRECT+map.getStatusCode());
						return ;

					}
					// 已经被拉黑 判断
					if (Constants.FA_STATUS_BLACK.equals(user.getFaStatus())) {
						logger.info("In apiweixin mpback checkUser Status 04");
						// 已经被拉黑
						map.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_BLACK);
						response.sendRedirect(WAP_SEND_REDIRECT+map.getStatusCode());
						return ;
					}
				}

				logger.info("In apiweixin mpback set seesion login!");
				Session session = SessionUtil.getSession(true);
				session.setLogin(true);
				session.setUser(user);
				SessionUtil.setSession(session);
				AuthenticationDTO auth = authenticationService
						.queryAuthInfo(user.getId());

				String returnUrl = (String) session.getAttribute("returnUrl");
				Map<String, Object> parameterMap = (Map<String, Object>) session
						.getAttribute("returnParameterMap");
				String returnMethod = (String) session
						.getAttribute("returnMethod");
				userinfo.append("&returnUrl=");
				userinfo.append(StringUtils.isBlank(returnUrl)?returnUrl:URLEncoder.encode(returnUrl));
				userinfo.append("&params=");
				userinfo.append(parameterMap);
				userinfo.append("&method=");
				userinfo.append(StringUtils.isBlank(returnMethod)?returnMethod:URLEncoder.encode(returnMethod));
				userinfo.append("&userType=");
				userinfo.append(user.getUType());
				userinfo.append("&uRole=");
				userinfo.append(user.getRole());
				userinfo.append("&reviewStatus=");
				userinfo.append("0");
				if (auth != null) {
					userinfo.append("&reviewStatus=");
					userinfo.append(StringUtils.isBlank(auth.getReviewStatus())?auth.getReviewStatus():URLEncoder.encode(auth.getReviewStatus()));
				}
				if (StringUtils.isBlank(user.getUserName())) {
					userinfo.append("&uName=");
					userinfo.append("");
				} else {
					userinfo.append("&uName=");
					userinfo.append(StringUtils.isBlank(user.getUserName())?user.getUserName():URLEncoder.encode(user.getUserName()));
				}

				FaUserDTO userTmp = new FaUserDTO();
				userTmp.setId(user.getId());
				userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
				userTmp.setLastLoginTime(new Date());
				userTmp.setLoginNum(user.getLoginNum()+1);
				userService.updateFaUserInfo(userTmp);
				userinfo.append("&id=");
				userinfo.append(user.getId());
				userinfo.append("&lastLoginIP=");
				userinfo.append(user.getLastLoginIP());
				userinfo.append("&lastLoginTime=");
				userinfo.append(user.getLastLoginTime());
				userinfo.append("&uImage=");
				userinfo.append(user.getuImage());
				userinfo.append("&nickname=");
				userinfo.append(StringUtils.isBlank(bean.getNickname())?bean.getNickname():URLEncoder.encode(bean.getNickname()));
				userinfo.append("&headimgurl=");
				userinfo.append(bean.getHeadimgurl());
				
			} else if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_WECHAT_ASSOCIATED_USER_ERROR.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");
				userinfo.append("&nickname=");
				userinfo.append(StringUtils.isBlank(bean.getNickname())?bean.getNickname():URLEncoder.encode(bean.getNickname()));
				userinfo.append("&headimgurl=");
				userinfo.append(bean.getHeadimgurl());
				
				//进行下一步关联用户操作.将openid设置到session
				super.getSession(true).setAttribute(WECHAT_OPENID,bean.getUnionid());
			}

			//页面跳转
			logger.info("###################################################"+request.getParameter("state"));
			String sendRedirect =	WeChatRedirectTemplteUtil.getWeChatRedirect(request.getParameter("state"));
			logger.info("###################################################"+(StringUtils.isBlank(sendRedirect)?WAP_SEND_REDIRECT:sendRedirect)+map.getStatusCode()+userinfo.toString());
			response.sendRedirect((StringUtils.isBlank(sendRedirect)?WAP_SEND_REDIRECT:sendRedirect)+map.getStatusCode()+userinfo.toString());

			logger.info("url:"+request.getRequestURL().toString());
			logger.info("seesion ID:"+SessionUtil.getHttpRequest().getRequestedSessionId());
		} catch (Exception e) {

			logger.error("In apiweixin mpback error!", e);
		}
		logger.info("In apiweixin mpback end!");

	}
	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法 (只认证不登录)
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/mpAnthBack/{a}/{b}")
	public void mpAnthBack(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String a,@PathVariable String b) {

		logger.info("In apiweixin mpback begin!");
		try {
			StringBuilder sb = new StringBuilder();
			//判断域名来源
			ResultMap checkMap = checkStg(request,response);
			if (STATUS.FAILE.equals(checkMap.getStatus())){
				return ;
			}
			
			ResultMap map = wechatCoreServiceImpl
					.mpCallback(request);
			logger.info("In apiweixin mpback ResultMap getStatusCode!"+map.getStatusCode());
			FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");
			super.getSession(true).setAttribute(WECHAT_OPENID,bean.getUnionid());
			
			//↓注入活动信息  begin
			HashMap<String,Object> activitesMap = new HashMap<String,Object>();
			activitesMap.put("faUserWechatDTO", (FaUserWechatDTO) map.getAttribute("object"));
			activitesService.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_WeChatWap_Join_Login, activitesMap);
			//↑注入活动信息  end
			
			//返回
			sb.append(WeChatGiftXMLUtil.map.get(WeChatGiftXMLUtil.MP_ANTH_BACK));
			sb.append(a);
			sb.append("/");
			sb.append(b);
			sb.append("?statusCode=");
			if(STATUS.SUCCESS.equals(map.getStatus())){
				sb.append(ResultMap.STATUS_CODE_SUCCESS);
			}else{
				sb.append(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			}
			logger.info("In apiweixin sendRedirect!"+sb.toString());
			response.sendRedirect(sb.toString());

		} catch (Exception e) {

			logger.error("In apiweixin mpback error!", e);
		}
		logger.info("In apiweixin mpback end!");

	}
	/**
	 * app 获取code 调用
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked" })
	@RequestMapping(value = "/appback")
	@ResponseBody
	public ResultMap appback(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		logger.info("In appback begin!");
		ResultMap result = new ResultMap();
		try {
			ResultMap map = wechatCoreServiceImpl
					.appCallback(request);
			StringBuffer userinfo = new StringBuffer();
			
			//输出状态码
			logger.info("In appback ResultMap getStatusCode!"+map.getStatusCode());
			// 已经关联
			if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_SUCCESS.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");

				UserDTO user = userService.queryUserById(bean.getUserId());
				
				if (user != null) {
					//查询是否活动中
					String start= "2016-01-01 00:00:00";
					String end = "2017-10-20 23:59:59";
					//判断时间
					Date inputDate = new Date();
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date d1 = sf.parse(start);
					Date d2 = sf.parse(end);
					 //在设定时间内 
					if(inputDate.before(d2) && inputDate.after(d1) && (user.getuShoprole()==null || !user.getuShoprole().equals("2"))){
						//修改状态为通过
						UserDTO ud = new UserDTO();
						ud.setId(user.getId());
						ud.setuShoprole("2"); //
						ud.setFpTempRole("1"); //活动通过标识
						user.setuShoprole("2");
						ud.setLoginName(user.getLoginName());
						userService.updateUser(ud);
					}
					
					
					// 用户状态验证
					if (Constants.FA_STATUS_DISABLE.equals(user.getFaStatus())) {
						logger.info("In apiweixin relationlogin checkUser Status 02");
						// 已经被禁用
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_DISABLE);
						return result;

					}
					// 已经被拉黑 判断
					if (Constants.FA_STATUS_BLACK.equals(user.getFaStatus())) {
						logger.info("In apiweixin relationlogin checkUser Status 02");
						// 已经被拉黑
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_BLACK);
						return result;
					}
				}
				
				logger.info("In appback set seesion login!");
				Session session = SessionUtil.getSession(true);
				session.setLogin(true);
				session.setUser(user);
				SessionUtil.setSession(session);

				AuthenticationDTO auth = null;
				if(user != null && StringUtils.isNotBlank(user.getId())) {
					auth = authenticationService
							.queryAuthInfo(user.getId());
				}

				String returnUrl = (String) session.getAttribute("returnUrl");
				Map<String, Object> parameterMap = (Map<String, Object>)session.getAttribute("returnParameterMap");
				String returnMethod = (String) session.getAttribute("returnMethod");
				result.setAttribute("returnUrl", returnUrl);
				result.setAttribute("params", parameterMap);
				result.setAttribute("method", returnMethod);
				
				result.setAttribute("userType", user.getUType());
				result.setAttribute("uRole", user.getRole());
				result.setAttribute("uEmail", user.getuEmail());
				result.setAttribute("reviewStatus", "0");
				result.setAttribute("uRemark",user.getRemark());
				result.setAttribute("loginName",user.getLoginName());
				if(auth!=null){
					result.setAttribute("reviewStatus", auth.getReviewStatus());
					result.setAttribute("trade", auth.getTrade());
					result.setAttribute("tradeAge", auth.getTradeAge());
				}
				if(StringUtils.isBlank(user.getUserName())){
					result.setAttribute("uName","");
				}else{
					result.setAttribute("uName",user.getUserName());
				}
				
				if(StringUtils.isBlank(user.getuRealName())) {
					result.setAttribute("uRealName","");
				} else {
					result.setAttribute("uRealName", user.getuRealName());
				}
				
				FaUserDTO userTmp = new FaUserDTO();
				userTmp.setId(user.getId());
				userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
				userTmp.setLastLoginTime(new Date());
				userTmp.setLoginNum(user.getLoginNum()+1);
				userService.updateFaUserInfo(userTmp);
				
				result.setAttribute("id",user.getId());
				result.setAttribute("lastLoginIP", user.getLastLoginIP());
				result.setAttribute("lastLoginTime", user.getLastLoginTime());
				result.setAttribute("uImage", user.getuImage());
				
				String token = user.getId();
				try {
					String sessionId = request.getRequestedSessionId();
					token = SecureUtil.encrypt(token).replaceAll("=", "");
					Cookie cookie = new Cookie(Constants._TOKEN, token);
					cookie.setMaxAge(60*60*24*15);
					cookie.setPath("/");
					response.addCookie(cookie);
					//android 
					
					result.setAttribute("token", token);
					result.setAttribute("phoneid", sessionId);
					
					log.info("MemcacheCacheHelper.mcc.set token:"+token);
					MemcacheCacheHelper.mcc.set(token,System.currentTimeMillis(),0 );
				} catch (Exception e) {
					log.error("mobile pt create token error!",e);
				}
				
				FaUserWechatDTO faUserWechatDTO =  new FaUserWechatDTO();
				faUserWechatDTO.setUserId(user.getId());
				faUserWechatDTO = userWechatServiceImpl.queryUserWechatInfo(faUserWechatDTO);
				if(faUserWechatDTO != null){
					Map<String, Object> faUserWechatMap = new HashMap<String, Object>();
					faUserWechatMap.put("headimgurl", faUserWechatDTO.getHeadimgurl());
					faUserWechatMap.put("nickname", faUserWechatDTO.getNickname());
					result.setAttribute("faUserWechatDTO",faUserWechatMap);
				}
				
				//查询店主个人信息
				try {
					ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
					//用户id
					shopperUserInfo.setUserId(user.getId());
					ShopperUserInfoDTO shopperUserInfoDto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);
					result.setAttribute("shopperUserInfoDto",shopperUserInfoDto);
				} catch (Exception e) {
					log.error("get ShopperUserInfoDTO error",e);
				}
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setMessage("登陆成功");
				return result;
				
				//未关联-提示用户关联  将openid 设置到session
			} else if (STATUS.SUCCESS.equals(map.getStatus()) && ResultMap.STATUS_CODE_WECHAT_ASSOCIATED_USER_ERROR.equals(map.getStatusCode())) {
				
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");
				userinfo.append(bean.getHeadimgurl());
				result.setAttribute("nickname", bean.getNickname());
				result.setAttribute("headimgurl", bean.getHeadimgurl());

				//进行下一步关联用户操作.将openid设置到session
				super.getSession(true).setAttribute(WECHAT_OPENID,bean.getUnionid());
				result.setStatus(map.getStatus());
				result.setStatusCode(map.getStatusCode());
				return result;
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("In  appback error!", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
		logger.info("In appback end!");

		return result;

	}
	/**
	 * 开放-生成登陆二维码URL
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/openlogin")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		logger.info("In apiweixin openlogin begin!");

		String openWeixinLogin = null;
		try {
			openWeixinLogin = wechatCoreServiceImpl.getOpenWeixinLogin(request);
		} catch (Exception e) {

			logger.error("In apiweixin openlogin error!", e);
		}

		response.sendRedirect(openWeixinLogin);

		logger.info("In apiweixin openlogin end!");
	}

	/**
	 * 开放-关联登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/relationlogin")
	@ResponseBody
	public ResultMap relationlogin(HttpServletRequest request, UserDTO user,
			HttpServletResponse response) throws IOException {

		logger.info("In apiweixin relationlogin begin!");
		ResultMap result = new ResultMap();
		try {
			// 1、验证登录用户合法  2、关联用户  3、登录
			result = wechatCoreServiceImpl.relationlogin(request, user);
			
			logger.info("In apiweixin relationlogin SUCCESS!");
		} catch (Exception e) {
			log.error("login error", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		logger.info("In apiweixin relationlogin end!");
		return result;
	}
	/**
	 * 开放-关联注册
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/relationregister")
	@ResponseBody
	public ResultMap relationRegister(HttpServletRequest request, RegisterDTO register,
			HttpServletResponse response) throws IOException {

		logger.info("In apiweixin relationRegister begin!");
		ResultMap result = new ResultMap();
		try {
			// 1、验证注册信息  2、创建用户 3、关联用户  4、登录
			result = wechatCoreServiceImpl.relationRegister(request, register);
			
			logger.info("In apiweixin relationRegister SUCCESS!");
		} catch (Exception e) {
			log.error("login error", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		logger.info("In apiweixin relationRegister end!");
		return result;
	}
	private ResultMap checkStg(HttpServletRequest request,HttpServletResponse response){
		ResultMap result = new ResultMap();
		String last = request.getParameter("last");
		//判断是否二次跳转
		if(!StringUtil.isNullOrEmptyStr(last)){
			result.setStatus(STATUS.SUCCESS);
			return result;
		}
		//如果为空的话 	return 	STATUS.SUCCESS
		String state = request.getParameter("state");
		if(StringUtil.isNullOrEmptyStr(state)){
			result.setStatus(STATUS.SUCCESS);
			return result;
		}
		String stateLastbit = state.substring(state.length()-1);
		if(!"0".equals(stateLastbit)){
			logger.info("################ mpback checkStg true ###################");
			logger.info("#:"+state);
			logger.info("#:"+stateLastbit);
			
			String mstg_send_redirect = WeChatMpbackRedirectUtil.getWeChatRedirect(stateLastbit);
			logger.info("#:"+mstg_send_redirect);

			if(StringUtils.isBlank(mstg_send_redirect)){
				mstg_send_redirect =  MSTG_SEND_REDIRECT;
			}
			mstg_send_redirect = mstg_send_redirect.replace("CODE", request.getParameter("code"));
			mstg_send_redirect = mstg_send_redirect.replace("STATE", request.getParameter("state"));

			//参数返回
			Map<String, Object> map = getParameterMap(request);
			if(map  != null && map.size() >0) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					mstg_send_redirect = mstg_send_redirect + "&" + entry.getKey() + "=" + entry.getValue();
				}
			}
			logger.info("#callBack:"+mstg_send_redirect);
			try {
				String url = request.getParameter("url");
                logger.info("#:"+url);
				if(StringUtils.isNotBlank(url) && mstg_send_redirect.indexOf("?")>=0){
					mstg_send_redirect  = mstg_send_redirect + "&url="+url;
				}
				logger.info("#:"+mstg_send_redirect);
				result.setStatus(STATUS.FAILE);
				response.sendRedirect(mstg_send_redirect);
			} catch (IOException e) {
				logger.error("checkStg error!", e);
			}	
		}else{
			result.setStatus(STATUS.SUCCESS);
		}
		return result;
	}

	@SuppressWarnings("deprecation")
	private ResultMap getfcsz(HttpServletRequest request,HttpServletResponse response,ResultMap map){
		ResultMap result = new ResultMap();
		String state = request.getParameter("state");
		StringBuffer userinfo = new StringBuffer();
		logger.info("into getfcsz begin");
		try {
			if("11".equals(state) || "10".equals(state) ){
				FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");
				userinfo.append("&nickname=");
				userinfo.append(StringUtils.isBlank(bean.getNickname())?bean.getNickname():URLEncoder.encode(bean.getNickname()));
				userinfo.append("&headimgurl=");
				userinfo.append(bean.getHeadimgurl());
				
				//将openid放入session，发财指数 活动使用 创建   by jiangtinglin
				logger.info("FCZS activies openId is :"+bean.getUnionid());
				super.getSession(true).setAttribute(Constants.ACTIVITIES_CODE_FCZS_SESSION_UNIONID,bean.getUnionid());
				
				logger.info("into Activies FCZS sendRedirect...url:"+WAP_SEND_ACTIVITES_REDIRECT+userinfo.toString());
				result.setStatus(STATUS.FAILE);
				response.sendRedirect(WAP_SEND_ACTIVITES_REDIRECT+userinfo.toString());
			}else{
				result.setStatus(STATUS.SUCCESS);
			}
		} catch (Exception e) {
			result.setStatus(STATUS.FAILE);
		}
		logger.info("into getfcsz end");
		return result;
	}
	
	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@RequestMapping(value = "/mpbackNotAuth")
	public void mpbackNotAuth(HttpServletRequest request,
			HttpServletResponse response) {

		logger.info("In apiweixin mpbackNotAuth begin!");
		try {
			//判断域名来源
			ResultMap checkMap = checkStg(request,response);
			if (STATUS.FAILE.equals(checkMap.getStatus())){
				return ;
			}
			
			ResultMap map = wechatCoreServiceImpl
					.mpCallbackNotAuth(request);
			StringBuffer userinfo = new StringBuffer();

			//输出状态码
			logger.info("In apiweixin mpback ResultMap getStatusCode!"+map.getStatusCode());
				
			//进行下一步关联用户操作.将openid设置到session
			super.getSession(true).setAttribute(WECHAT_OPENID,map.getAttribute("openId"));

			//页面跳转
			logger.info("###################################################"+request.getParameter("state"));
			String state = request.getParameter("state");
			String[] s = state.split(",");
			String sendRedirect ;
			if(s.length>1){
				sendRedirect = WeChatRedirectTemplteUtil.getWeChatRedirect(s[0])+map.getStatusCode()+"&openId="+map.getAttribute("openId")+"&oid="+s[1];
			}else{
				 sendRedirect =	WeChatRedirectTemplteUtil.getWeChatRedirect(s[0])+map.getStatusCode()+"&openId="+map.getAttribute("openId")+"&oid=";
			}
			
			logger.info("###################################################"+sendRedirect);
			response.sendRedirect(sendRedirect);

		} catch (Exception e) {

			logger.error("In apiweixin mpback error!", e);
		}
		logger.info("In apiweixin mpback end!");

	}
	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法-静默授权
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/mpbackJm")
	public void mpbackJm(HttpServletRequest request,
			HttpServletResponse response) {

		logger.info("In apiweixin mpbackJm begin!");
		try {
			//判断域名来源
			ResultMap checkMap = checkStg(request,response);
			if (STATUS.FAILE.equals(checkMap.getStatus())){
				return ;
			}
			
			ResultMap map = wechatCoreServiceImpl
					.mpCallbackNotAuth(request);
			
			String  statusCode = map.getStatusCode(); 
			String openId = (String) map.getAttribute("openId");

			//输出状态码
			logger.info("In apiweixin mpbackJm ResultMap getStatusCode!"+statusCode);
			logger.info("In apiweixin mpbackJm ResultMap openId!"+openId);
				
			//进行下一步关联用户操作.将openid设置到session
			super.getSession(true).setAttribute(OPENID,openId);

			//页面跳转
			logger.info("###################################################"+request.getParameter("state"));
			String state = request.getParameter("state");
			
			String sendRedirect = "";
			
			String[] states = null;
			
			
			// state[0]  - 前端 路由   
			// state[1]  - 标识
			if(StringUtils.isNotBlank(state)){
				
				
				logger.info("state:"+state);
				
				states  = state.split("@");
				
				logger.info("state[0]:"+(states.length>0?states[0]:null));
				
				logger.info("state[1]:"+(states.length>1?states[1]:null));
				
				//页面跳转
				sendRedirect =	WeChatRedirectTemplteUtil.getWeChatRedirect(states.length>1?states[1]:null);
				
			}
			
			String route =  states.length>0?states[0]:"";
			
			if(route.indexOf("?") >=0){
				route = route + "&";
			}else{
				route = route + "?";
			}
			
			
			response.sendRedirect(sendRedirect+route+"statusCode="+statusCode);

			logger.info("sendRedirect:"+sendRedirect);

		} catch (Exception e) {

			logger.error("In apiweixin mpback error!", e);
		}
		logger.info("In apiweixin mpback end!");

	}

	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法--不自动登录
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@RequestMapping(value = "/mpbackNoLogin")
	public void mpbackNoLogin(HttpServletRequest request,
					   HttpServletResponse response) {

		logger.info("In apiweixin mpback begin!");
		try {

			ResultMap map = wechatCoreServiceImpl
					.mpCallback(request);
			StringBuffer userinfo = new StringBuffer();

			//输出状态码
			logger.info("In apiweixin mpback ResultMap getStatusCode!"+map.getStatusCode());

			String  statusCode = map.getStatusCode();
			FaUserWechatDTO bean = (FaUserWechatDTO) map.getAttribute("object");

            //页面跳转
            logger.info("###################################################"+bean.getOpenid());
            logger.info("###################################################"+bean.getMpOpenid());
			logger.info("###################################################"+bean.getMpOpenid()==null?bean.getOpenid():bean.getMpOpenid());

			//进行下一步关联用户操作.将openid设置到session
			super.getSession(true).setAttribute(OPENID,bean.getMpOpenid()==null?bean.getOpenid():bean.getMpOpenid());
			SessionUtil.setSession(super.getSession(true));

			//页面跳转
			logger.info("###################################################"+request.getParameter("state"));
			String state = request.getParameter("state");

			String sendRedirect = "";

			String[] states = null;


			// state[0]  - 前端 路由
			// state[1]  - 标识
			if(StringUtils.isNotBlank(state)){


				logger.info("state:"+state);

				state  = state.replaceAll("L0L","&");

				logger.info("state:"+state);

				states  = state.split("@");

				logger.info("state[0]:"+(states.length>0?states[0]:null));

				logger.info("state[1]:"+(states.length>1?states[1]:null));

				//页面跳转
				sendRedirect =	WeChatRedirectTemplteUtil.getWeChatRedirect(states.length>1?states[1]:"70");

			}

			String route =  states.length>0?states[0]:"";

			if(route.indexOf("?") >=0){
				route = route + "&";
			}else{
				route = route + "?";
			}

			response.sendRedirect(sendRedirect+route+"statusCode="+statusCode);

			logger.info("sendRedirect:"+sendRedirect);
		} catch (Exception e) {

			logger.error("In apiweixin mpback error!", e);
		}
		logger.info("In apiweixin mpback end!");

	}


}
